import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/login.vue'
import { useUserStore } from '@/stores/user'
import { firstRoutePath, setAutherRouter } from './autherRoute'
import NotAuth from '@/views/not-auth.vue'

export const baseRoutes = [
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      title: '登录',
      icon: 'UserFilled',
      type: '1',
    },
    children: [],
  },
  {
    path: '/not-auth',
    name: 'not-auth',
    component: NotAuth,
    meta: {
      title: '没有权限',
      icon: 'UserFilled',
      type: '1',
    },
    children: [],
  },
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...baseRoutes],
})

const witeRoutes: any = ['/login', '/logout']

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const useUser: any = useUserStore()
  const userInfo = useUser.userInfo
  if (witeRoutes.indexOf(to.path) >= 0) {
    next()
  } else {
    if (userInfo && userInfo.username) {
      if (!hasRouteFun(to.path)) {
        //设置路由
        setAutherRouter(userInfo.rolesMenus)

        if (to.path == '/') {
          next(firstRoutePath)
        } else {
          if (!hasRouteFun(to.path)) {
            // 不存在
            next('/not-auth')
          } else {
            next({
              path: to.path,
              replace: true,
            })
          }
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  }
})

const hasRouteFun = (path: any) => {
  const routes = router.getRoutes()
  let hasRoute = false
  routes.forEach((route: any) => {
    if (route.path == path) {
      hasRoute = true
    }
  })
  return hasRoute
}

export default router
